package com.duqc.springbatch;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @ClassName TimeTask
 * @Description 运行JOB，一种是把Job对象注入到Spring容器里，这里是定时任务
 * @Author duqc
 * @Date 2022/7/18
 **/
@Slf4j
@Component
public class TimeTask {

    private final JobLauncher jobLauncher;

    private final DataBatchJob dataBatchJob;

    public TimeTask(JobLauncher jobLauncher, DataBatchJob dataBatchJob) {
        this.jobLauncher = jobLauncher;
        this.dataBatchJob = dataBatchJob;
    }

    @SneakyThrows
//    @Scheduled(cron = "0/10 * * * * ?")
    public void runBatch() {
        log.info("定时任务执行了...");
        //在运行一个job的收需要添加至少一个参数，这个参数最后会被写到batch_job_execution_params表中，
        //不添加这个参数的话，job不会运行，并且这个参数在表中不能重复，若设置的参数已存在表中，则会抛出异常
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("timestamp", System.currentTimeMillis())
                .toJobParameters();
        //获取job并运行
        Job job = dataBatchJob.dataHandleJob();
        JobExecution execution = jobLauncher.run(job, jobParameters);
        log.info("定时任务结束. Exit Status : {}", execution.getStatus());
    }

}
